package com.algorithm;

import java.util.Arrays;

/**
 * @author: sun.hongliang
 * @create: 2019/12/05 11:42
 */
public class FourSumCountTest {
    public static void main(String[] args) {

    }

    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
        int sum = 0;
        int lenA = A.length;
        int lenB = B.length;
        int lenC = C.length;
        int lenD = D.length;
        Arrays.sort(C);
        Arrays.sort(D);
        for (int i = 0; i < lenA; i++) {
            int tempA = A[i];
            for (int j = 0; j < lenB; j++) {
                int tempB = B[j];
                for (int cl = 0, dm = lenD - 1; cl <= lenC - 1 && dm >= 0; ) {
                    if (C[cl] + D[dm] == -tempA - tempB) {
                        sum++;
                        while (cl < lenC - 1 && C[cl] == C[cl + 1]) {
                            sum++;
                            cl++;
                        }
                        while (dm > 0 && D[dm] == D[dm - 1]) {
                            sum++;
                            dm--;
                        }
                        cl++;
                        dm--;
                    } else if (C[cl] + D[dm] > -tempA - tempB) {
                        dm--;
                    } else {
                        cl++;
                    }
                }
            }
        }
        return sum;
    }
}
